package com.thirteen.app.controller;

import com.thirteen.app.entity.User;
import com.thirteen.app.service.UserService;
import com.thirteen.app.utils.JWTUtils;
import com.thirteen.app.utils.tools.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.oas.annotations.EnableOpenApi;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaomin_2017013792_CS181
 * @version 1.0
 * @date 2021/9/12 9:55
 */
@CrossOrigin
@Api(tags = "登录模块")
@EnableOpenApi
@RestController
@RequestMapping("/api")
public class LoginController {
    @Resource
    private UserService userService;

    @ApiOperation("登陆")
    @PostMapping("/login")
    public CommonResult login(@RequestBody User user) {
        System.out.println("用户名：" + user.getUserName());
        System.out.println("密码：" + user.getPassWord());
        System.out.println("登录地点：" + user.getProvince() + user.getCity());
        Map<String, Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);
            if (userDB != null) {
                userDB.setProvince(user.getProvince());
                userDB.setCity(user.getCity());
//                更新用户登录地点
                userService.updateUserAddress(userDB);
            }
            userDB.setPassWord("");

            String token = JWTUtils.getToken(userDB);

            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("userInfo", userDB);
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", "认证失败");
        }

        return CommonResult.success(map);
    }
}
